#*** GOOGLE CALENDAR EXPORT  ***
import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow, AccessTokenCredentials
from oauth2client.tools import run

import time
import datetime

import json



myDeveloperKey = 'AIzaSyDtBY5D-mT8NBbO1o0u8w8jxq8QBpR2deg'



def google_calendar_export (calEvents, accessToken):

    credentials = AccessTokenCredentials(accessToken,
                                         'WellGO Calendar/1.0')

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)
        
        
    # Build a service object for interacting with the API. Visit
    # the Google APIs Console
    # to get a developerKey for your own application.
    service = build(serviceName='calendar', version='v3', http=http,
                    developerKey= myDeveloperKey)


    #INSERT NEW CALENDAR

    # Once Authenticated, send a POST Request to insert a new Calendar
    # into User's calendar list
    calendar = {
        'summary': 'WVU Lego Calendar',
        'timeZone': 'America/New_York'
        }

    created_calendar = service.calendars().insert(body=calendar).execute()


    # Now Insert all the Events:  
    for e in calEvents:
        event = {
            'summary': e['summary'],
            'start': {
                'dateTime': e['startTime'],
                'timeZone': 'America/New_York'
                },
            'end': {
                'dateTime': e['endTime'],
                'timeZone': 'America/New_York'
                },
            'recurrence': [
                'RRULE:FREQ=WEEKLY;COUNT=5',
                ]
            }

        recurring_event = service.events().insert(calendarId=created_calendar['id'], body=event).execute()
